package com.yonyou.gmmc.service.pointactivity.controller;



import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dms.http.HttpCommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.gmmc.service.pointactivity.constant.PointActivityConstant;
import com.yonyou.gmmc.service.pointactivity.model.QuestionBo;
import com.yonyou.gmmc.service.pointactivity.model.TmDealer;
import com.yonyou.gmmc.service.pointactivity.model.TmRegion;
import com.yonyou.gmmc.service.pointactivity.model.TmSweepstake;
import com.yonyou.gmmc.service.pointactivity.model.TtReturnFactoryReserve;
import com.yonyou.gmmc.service.pointactivity.model.TtQneResult;
import com.yonyou.gmmc.service.pointactivity.service.LotteryService;
import com.yonyou.gmmc.service.pointactivity.service.NotReturnFactoryService;
import com.yonyou.gmmc.service.pointactivity.service.QuestionnaireService;
import com.yonyou.gmmc.service.pointactivity.service.ReservationService;
import com.yonyou.gmmc.service.pointactivity.util.DateUtils;
import com.yonyou.gmmc.service.pointactivity.util.StringUtils;

import io.swagger.annotations.Api;

/*
 * 一年内未返厂
 */
@RestController
@RequestMapping(value = PointActivityConstant.BASE_PATH + "/" + PointActivityConstant.VERSION)
@Api("一年内未返厂")
public class NotReturnFactoryController {

	private Logger logger = Logger.getLogger(NotReturnFactoryController.class);

	@Autowired
	private NotReturnFactoryService notReturnFactoryService;

	@Autowired
	private QuestionnaireService questionnaireService;
	
	@Autowired
	private LotteryService lotteryService;

	// 注入省份查询及奖券初始化业务层
	@Autowired
	private ReservationService reservationService;

	// 活动类型
	private Integer ACTIVITY_TYPE = 1;
	// 操作人
	private Long OPERATION_BY = 999999999L;
//	// 问卷名称
//	private String qneTitle = "流失客户调查问卷";

	//private String url="http://172.16.96.136:7001/DCMS/common/iclub/IC999/excute.json";//测试活动同步URL地址
	private String url="http://dcms.gmmc.com.cn/DCMS/common/iclub/IC999/excute.json";//生产环境同步地址，测试勿用
	
	/**
	 * 这个方法会在当前这个类(Controller)任何一个方法调用之前调用一次
	 * 
	 * @param req
	 */
	@ModelAttribute
	public void recordVisit(HttpServletRequest req) {
		String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
		//openId = null == openId ? "oXrcfuMurfstpfdUIwDyEYb5x8Og" : openId;
		try {

			if (StringUtils.isNull(openId))
				throw new Exception("openId为空.!");
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("openId", openId);
			param.put("activityType", ACTIVITY_TYPE);
			//判断是否获取到用户所在省份地址信息
			 if(req.getParameter("province")==null || "".equals(req.getParameter("province"))){
				 //当省份为空时，查询用户所购车辆所在地省份
				 String province=reservationService.getCarAndProvince(openId);
				 param.put("province", province); 
			 }else {
				param.put("province", req.getParameter("province"));
			}
			param.put("createBy", OPERATION_BY);
			param.put("updateBy", OPERATION_BY);

			notReturnFactoryService.recordVisit(param);
		} catch (Exception e) {
			logger.info("一年内未返厂活动-记录用户访问次数.获取到openId:" + openId + ",访问记录异常.");
		}
	}
	
	@RequestMapping(value = "/checkUserProgress", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> checkUserPower(HttpServletRequest req) {

		String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);

		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {

			//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;

			if (StringUtils.isNull(openId))
				throw new Exception("openId为空.!");

			logger.info("一年内未返厂活动获取到的openId为:" + openId);

			resultMap = notReturnFactoryService.checkUserProgress(openId);

		} catch (Exception e) {
			logger.info("一年内未返厂活动-记录用户访问次数.获取到openId:" + openId + ",检查用户权限错误.");
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			resultMap.put(ResultMsgConstants.ERR_MSG, "一年内未返厂活动异常");
			resultMap.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return resultMap;
	}

	/**
	 * 查询当前问卷题目信息
	 * 
	 * @param req
	 * @return 当前题目信息
	 */
	@RequestMapping(value = "/queryQuestion", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody QuestionBo queryQuestion(HttpServletRequest req) {

		QuestionBo questionBo = new QuestionBo();

		Map<String, Object> mapError = new HashMap<String, Object>();

		try {
			
			String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
			//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;

			String userId = questionnaireService.getUserId(openId);

			if (StringUtils.isNull(userId)) {
				mapError.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
				mapError.put(ResultMsgConstants.ERR_MSG, "客户userId获取失败!");
				mapError.put(ResultMsgConstants.QUERY_DATA, "");
				questionBo.setError(mapError);
				return questionBo;
			}

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("userId", userId);
			param.put("qneTitle", PointActivityConstant.QNE_TITLE);

			QuestionBo bo = questionnaireService.queryQuestion(param);

			questionBo = bo;
			
			if (null == bo)
				throw new Exception("查询题目信息失败!");

			bo.setOwnerId(Long.valueOf(userId));
			bo.setqId(Long.valueOf(questionnaireService.queryId(param)));

		} catch (Exception e) {
			logger.error(new Exception(e));
			mapError.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			mapError.put(ResultMsgConstants.ERR_MSG, "查询当前题目信息失败!");
			mapError.put(ResultMsgConstants.QUERY_DATA, "");
			questionBo.setError(mapError);
		}
		return questionBo;
	}

	public void checkParam(Map<String, Object> param) throws Exception {
		for (String key : param.keySet()) {
			if(!"answerNo".equals(key)){
				if (StringUtils.isNull(String.valueOf(param.get(key))))
					throw new Exception("key:" + key + ".参数为空");
			}
		}
	}

	/**
	 * 跳转下一题，并保存答题记录
	 * 
	 * @param req
	 * @return 下一题题目信息
	 */
	@RequestMapping(value = "/queryNextQuestionByQtnNo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody QuestionBo queryNextQuestionByQtnNo(HttpServletRequest req) {
		Map<String, Object> param = new HashMap<>();
		Map<String, Object> mapError = new HashMap<String, Object>();
		QuestionBo questionBo = new QuestionBo();
		param.put("qneTitle", PointActivityConstant.QNE_TITLE);
		try{
			String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
			//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;
			param.put("openId", openId);
			boolean isAnswer = questionnaireService.isAnswer(param);
			if(isAnswer){
				questionBo.setQtnNo(Long.valueOf("0"));
				return questionBo;
			}
		}
		catch (Exception e) {
			logger.error(new Exception(e));
			mapError.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			mapError.put(ResultMsgConstants.ERR_MSG, "查询答题进度失败！");
			mapError.put(ResultMsgConstants.QUERY_DATA, "");
			questionBo.setError(mapError);
			return questionBo;
		}
		
		param.put("qId", StringUtils.isNull(req.getParameter("qId")) ? "" : req.getParameter("qId"));
		param.put("qneId", StringUtils.isNull(req.getParameter("qneId")) ? "" : req.getParameter("qneId"));
		param.put("qtnId", StringUtils.isNull(req.getParameter("qtnId")) ? "" : req.getParameter("qtnId"));
		param.put("qtnNo", StringUtils.isNull(req.getParameter("qtnNo")) ? "" : req.getParameter("qtnNo"));
		param.put("answer", StringUtils.isNull(req.getParameter("answer")) ? "" : req.getParameter("answer"));
		param.put("userId", StringUtils.isNull(req.getParameter("ownerId")) ? "" : req.getParameter("ownerId"));
		param.put("answerNo", StringUtils.isNull(req.getParameter("answerId")) ? "" : req.getParameter("answerId"));

		try {
			checkParam(param);

			TtQneResult ttQneResult = new TtQneResult();
			ttQneResult.setUserAnswer(String.valueOf(param.get("answer")));
			ttQneResult.setOwnerId(Long.valueOf(String.valueOf(param.get("userId"))));
			ttQneResult.setQneId(Long.valueOf(String.valueOf(param.get("qneId"))));
			ttQneResult.setQtnId(Long.valueOf(String.valueOf(param.get("qtnId"))));
			ttQneResult.setSubmitTime(new Date());
			ttQneResult.setUserQneRefId(Long.valueOf(String.valueOf(param.get("qId"))));
			
			if(StringUtils.isNull(String.valueOf(param.get("answerNo"))))
				ttQneResult.setAnswerNo(0);
			else
				ttQneResult.setAnswerNo(Integer.valueOf(String.valueOf(param.get("answerNo"))));
				

			questionnaireService.saveAnswer(param, ttQneResult);
			
		} catch (Exception e) {
			logger.error(new Exception(e));
			mapError.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			mapError.put(ResultMsgConstants.ERR_MSG, "保存当前答题记录失败！");
			mapError.put(ResultMsgConstants.QUERY_DATA, "");
			questionBo.setError(mapError);
			return questionBo;
		}

		try {
			QuestionBo bo = questionnaireService.queryNextQuestionByQtnNo(param);
			questionBo = bo;
			questionBo.setqId(Long.valueOf(String.valueOf(param.get("qId"))));
			questionBo.setOwnerId(Long.valueOf(String.valueOf(param.get("userId"))));

			return questionBo;
		} catch (Exception e) {
			logger.error(new Exception(e));
			mapError.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			mapError.put(ResultMsgConstants.ERR_MSG, "查询下一题失败！");
			mapError.put(ResultMsgConstants.QUERY_DATA, "");
			questionBo.setError(mapError);
			return questionBo;
		}
	}

	/**
	 * 跳转上一题
	 * 
	 * @param req
	 * @return 上一题题目信息
	 */
	@RequestMapping(value = "/queryLastQuestionByQtnNo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody QuestionBo queryLastQuestionByQtnNo(HttpServletRequest req) {
		Map<String, Object> map = new HashMap<>();
		QuestionBo questionBo = new QuestionBo();
		Map<String, Object> mapError = new HashMap<String, Object>();
		map.put("qneTitle", PointActivityConstant.QNE_TITLE);
		try{
			String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
			//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;
			map.put("openId", openId);
			boolean isAnswer = questionnaireService.isAnswer(map);
			if(isAnswer){
				questionBo.setQtnNo(Long.valueOf("0"));
				return questionBo;
			}
		}
		catch (Exception e) {
			logger.error(new Exception(e));
			mapError.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			mapError.put(ResultMsgConstants.ERR_MSG, "查询答题进度失败！");
			mapError.put(ResultMsgConstants.QUERY_DATA, "");
			questionBo.setError(mapError);
			return questionBo;
		}
		String qtnNo = req.getParameter("qtnNo");
		String ownerId = req.getParameter("ownerId");
		String qId = req.getParameter("qId");
		String qneId = req.getParameter("qneId");
		String qtnId = req.getParameter("qtnId");
		
		map.put("qneTitle", PointActivityConstant.QNE_TITLE);
		map.put("qtnNo", qtnNo);
		map.put("userId", ownerId);
		map.put("qneId", qneId);
		map.put("qtnId", qtnId);
		
		try {
			QuestionBo bo = questionnaireService.queryLastQuestionByQtnNo(map);
			questionBo = bo;
			questionBo.setqId(Long.valueOf(qId));
			questionBo.setOwnerId(Long.valueOf(ownerId));
		} catch (Exception e) {
			logger.error(new Exception(e));
			mapError.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			mapError.put(ResultMsgConstants.ERR_MSG, "查询上一题失败！");
			mapError.put(ResultMsgConstants.QUERY_DATA, "");
		}
		questionBo.setError(mapError);
		return questionBo;
	}

	/**
	 * 判断问卷是否存在
	 * 
	 * @param req
	 * @return 客户对应问卷号
	 */
	@RequestMapping(value = "/questionnairIfExist", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> questionnairIfExist(HttpServletRequest req) {
		Map<String, Object> map = new HashMap<>();
		try {
			String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
			//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;
			map.put("qneTitle", PointActivityConstant.QNE_TITLE);
			map.put("userId", questionnaireService.getUserId(openId));
			map.put("qId", questionnaireService.questionnaireIfExist(map));
		} catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "客户问卷生成失败！");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}
	
	@RequestMapping(value = "/drawLottery", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public synchronized @ResponseBody Map<String, Object> drawLottery(HttpServletRequest req) {
		String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
		//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;
//		String openId = req.getParameter("openId");
		
		Map<String, Object> map = new HashMap<>();
		try{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date endDate = null;
			endDate = format.parse(lotteryService.getDrawEndTime());
			
			if(DateUtils.getDaysInMonth(new Date()) > DateUtils.getDaysInMonth(endDate)){
				map.put("drawMessage", "4");
				return map;
			}
			
			String province = lotteryService.getUserProvince(openId);
			if(province == null || "".equals(province)){
				map.put("drawMessage", "1");
				return map;
			}
			String ifDrawLottery = lotteryService.ifDrawLottery(openId);
			if(ifDrawLottery == null || "".equals(ifDrawLottery)){
				map.put("drawMessage", "2");
				return map;
			}
			if("NO".equals(ifDrawLottery)){
				String qtnNo = questionnaireService.getQtnNoByOpenId(openId, PointActivityConstant.QNE_TITLE);
				String ifWin = lotteryService.drawLottery(openId, province,qtnNo);
				if(ifWin == null || "".equals(ifWin)){
					map.put("drawMessage", "3");
					return map;
					}
				map.put("drawMessage", ifWin);
				}
			else{
				map.put("drawMessage", ifDrawLottery);
				return map;
				}
			}
		catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "抽奖失败！");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}
	
	@RequestMapping(value = "/ifDraw", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> ifDraw(HttpServletRequest req) {
		String openId = req.getHeader(PointActivityConstant.HEADER_OPENID);
		//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;
		Map<String, Object> map = new HashMap<>();
		try {
			String ifDraw = lotteryService.ifDrawLottery(openId);
			if(ifDraw == null || "".equals(ifDraw)){
				map.put("ifDrawMessage", "1");
				return map;
			}
			else{
				map.put("ifDrawMessage", ifDraw);
			}
			
		} catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "查询抽奖记录失败！！");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}
	
	@RequestMapping(value = "/lotteryDistribute", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> lotteryDistribute(HttpServletRequest req) {
		Map<String, Object> map = new HashMap<>();
		int param = Integer.valueOf(req.getParameter("day"));
		try {
			lotteryService.lotteryDistribute(param);
			map.put("distribute", "分配奖券成功！");
		} catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "奖券分配异常！");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}

	/**
	 * 查询省份
	 */
	@RequestMapping(value = "/province", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> findByProvince() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = reservationService.getProvince();
		} catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "省份查询异常");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}

	/**
	 * 根据省份查询城市列表
	 */
	@RequestMapping(value = "/city", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> findByCity(@RequestParam("regionCode") String regionCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = reservationService.getCity(regionCode);
		} catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "城市查询异常");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}

	/**
	 * 根据城市名称查询当地经销商
	 */
	@RequestMapping(value = "/dealer", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> findByDealer(@RequestParam("regionCode") String regionCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = reservationService.getDealer(regionCode);
		} catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "经销商查询异常");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}

	/**
	 * 查询活动时间区间
	 */
	@RequestMapping(value = "/getTime", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> findByTime() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = reservationService.getTime();
		} catch (Exception e) {
			logger.error(new Exception(e));
			map.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			map.put(ResultMsgConstants.ERR_MSG, "活动时间查询异常");
			map.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return map;
	}

	/**
	 * 保存车主预约信息
	 */
	public String savaReservation(TtReturnFactoryReserve reserve) {
		String str =null;
		try {
			//查询预约表openId是否存在
			String oId=reservationService.findByOpenId(reserve.getOpenId());
			 if(oId!=null){
				 str="重复预约异常";
			 }else {
				 //保存预约信息并返回主键
				 Integer code = reservationService.saveReserve(reserve);
				 if(code!=null){
					 try {
						 //调用CommonUtil工具类方法向dcms系统发送数据
						 Map<String, Object>map=new HashMap<String, Object>();
						 //查询vin码
						 String vin=reservationService.findByVin(reserve.getOpenId());
						 //活动奖券编码
						 TmSweepstake sweepstake=lotteryService.findByLottery(reserve.getOpenId());
						 map.put("vin", vin);
						 map.put("lotNum", sweepstake.getTmSweepstakeCode());
						 //map.put("actId", "2100000923");//测试用同步数据活动编号
						 map.put("actId", "1100001345"); //生产环境同步数据的活动编号，测试勿用！
						List<Object>list=HttpCommonUtil.getOwnerInfo(map, "IC999", url, Object.class);
						System.out.println(list.get(0).toString());
						if (list == null || list.size() == 0) {
							logger.error("数据传输错误");
			            }
					} catch (Exception e) {
						logger.error(new Exception(e));
					}
					 str="预约成功";
				 }
			}
		} catch (Exception e) {
			logger.error(new Exception(e));
		}
		return str;
	}

	/**
	 * 抽奖初始化方法
	 */
	@RequestMapping(value = "/initialize", method = RequestMethod.POST)
	public void Initialize() {
		try {
			reservationService.sweepstakeInit();
		} catch (Exception e) {
			logger.error(new Exception(e));
		}
	}
	
	/**
	 * 根据客户GPS定位所在省份查询当前省份剩余奖券
	 */
	@RequestMapping(value="/findByIalize", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> findByIalize(){
		Map<String, Object> resultmap = new HashMap<String, Object>();
		try { 
			//调用service层根据省份名称查询奖券数量
			List<TmSweepstake>list=lotteryService.getLottery();
			resultmap.put("sum", list.size());
		} catch (Exception e) {
			logger.error(new Exception(e));
			resultmap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			resultmap.put(ResultMsgConstants.ERR_MSG, "剩余奖券查询异常");
			resultmap.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return resultmap;
	}
	
	
	/**
	 * 根据openId查询客户中奖信息
	 */
	@RequestMapping(value="/findUserAndIalize", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> findUserAndIalize(HttpServletRequest request){
		Map<String, Object>resultmap=new HashMap<String,Object>();
		try {
			//获得openId
			String openId = request.getHeader(PointActivityConstant.HEADER_OPENID);
			//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;
			if (StringUtils.isNull(openId)){
				throw new Exception("openId为空!");				
			}
			//查询中奖信息劵号
			TmSweepstake sweepstake=lotteryService.findByLottery(openId);
			if(sweepstake!=null){				
				resultmap.put(sweepstake.getTmSweepstakeKey(), sweepstake.getTmSweepstakeCode());
			}
		} catch (Exception e) {
			logger.error(new Exception(e));
			resultmap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			resultmap.put(ResultMsgConstants.ERR_MSG, "客户奖券查询异常");
			resultmap.put(ResultMsgConstants.QUERY_DATA, "");
		}
		return resultmap;
	}
	
	/*
	 * 预约信息验证方法
	 */
	@RequestMapping(value="/verification", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> verification(HttpServletRequest request,TtReturnFactoryReserve reserve,@RequestParam("reservedate") String reservedate){
		Map<String, Object>map=new HashMap<String,Object>();
		TtReturnFactoryReserve factoryReserve=new TtReturnFactoryReserve();
		try {
			//获取openId
			String openId = request.getHeader(PointActivityConstant.HEADER_OPENID);
			//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;   
			//openId = null == openId ? "oXrcfuGDbsFT2f9amqa6j45_EuIY" : openId;
			if (StringUtils.isNull(openId)){
				throw new Exception("openId为空!");				
			}else {
			//校验省份字段
			if(reserve.getProvince()!=null||!("".equals(reserve.getProvince()))){
				TmRegion region=reservationService.checkOutProvince(reserve.getProvince());
				if(region.getRegionName()!=null){
					factoryReserve.setProvince(region.getRegionName());
				}else {
					map.put("message", "您选择的省份为非法省份！");
				}
			}else {
				map.put("message", "所选省份为空！");
			}
			//校验城市
			if(reserve.getCity()!=null||!("".equals(reserve.getCity()))){
				TmRegion region=reservationService.checkOutCity(reserve.getCity());
				if (region!=null) {
					factoryReserve.setCity(region.getRegionName());
				}else {
					map.put("messget", "您选择的城市为非法城市！");
				}
			}else {
				map.put("message", "所选城市为空！");
			}
			//校验经销商名称
			if(reserve.getDealerCode()!=null||!("".equals(reserve.getDealerCode()))){
			   TmDealer dealer=reservationService.chenkOutDealer(reserve.getDealerCode());
			   if (dealer!=null) {
				   factoryReserve.setDealerCode(dealer.getDealerCode());
				   factoryReserve.setDealerName(dealer.getDealerName());
			   }else {
				map.put("message", "指定经销商不存在!");
			   }
			}else {
				map.put("message", "所选经销商为空！");
			}
			//校验预约日期
			if(reservedate!=null||!("".equals(reservedate))){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date = sdf.parse(reservedate);
				factoryReserve.setReserveDate(date);
			}else {
				map.put("message", "预约时间必须选择！");
			}
			//验证无误调用保存方法
			factoryReserve.setOpenId(openId);
			factoryReserve.setCreateDate(new Date());
			String cod=savaReservation(factoryReserve);
			map.put("message", cod);
		  }
		} catch (Exception e) {
			logger.error(new Exception(e));
		}
		return map;
	}
	
	/**
	 * 查询客户是否已经预约
	 */
	@RequestMapping(value="/getByOpenId", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public @ResponseBody Map<String, Object> getByOpenId(HttpServletRequest request){
		Map<String, Object>resultmap=new HashMap<String,Object>();
		try {
			//获得openId
			String openId = request.getHeader(PointActivityConstant.HEADER_OPENID);
			//openId = null == openId ? "oXrcfuC1R4wosEPeJOHR7BPqaAOo" : openId;
			if (StringUtils.isNull(openId)){
				throw new Exception("openId为空!");				
			}
			//查询是否预约
			String oId=reservationService.findByOpenId(openId);
			if(oId!=null){
				resultmap.put("message", oId);
			}
		} catch (Exception e) {
			logger.error(new Exception(e));
			resultmap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
			resultmap.put(ResultMsgConstants.ERR_MSG, "查询预约异常");
			resultmap.put(ResultMsgConstants.QUERY_DATA, "");
		}
			return resultmap;
	}
}
